import env from "../../../utils/env"
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 1,
    // 搜索
    serach_pro: "",
    prosum: null,
    oriProlist: [],
    prolist: [
      // {
      //   bankId: '',
      //   bankName: '全部分支行'
      // }
    ],
    loading: true,
    showSelect: false,
    typeName: '全选',
    bankId: '',
    bankIds: [],
    FilePath: '',
    bankLevel: '',
    corpRole: wx.getStorageSync('userInfo').corpRole,
    batchId: ''
  },
  goOnChange(e) {
    this.setData({
      serach_pro: e.detail,
    });
  },
  selectAll(e) {
    if (e.currentTarget.dataset.key === '全选') {
      this.data.prolist.forEach(pre => pre.show = true)
      this.setData({
        typeName: '取消全选',
        prolist: this.data.prolist
      })
    } else {
      this.data.prolist.forEach(pre => pre.show = false)
      this.setData({
        typeName: '全选',
        prolist: this.data.prolist
      })
    }

  },
  async openMethod() {
    this.setData({
      bankIds: []
    })
    // 统计所有选择的支行
    this.data.prolist.forEach(val => {
      if (val.show) {
        this.data.bankIds.push(val.bankId)
      }
    })
    if (this.data.bankIds.length === 0) {
      wx.showToast({
        title: "请至少选择一家银行进行导出",
        icon: 'none'
      })
    } else {
      console.log('到这里')
      const res = await this.download()
      setTimeout(function () {
        wx.hideLoading();
      }, 200);
      this.setData({
        showSelect: true,
      });
    }
    // console.log(this.data.bankIds, 'bankIds')
  },
  async downloadWx() {
    const _this = this
    // const res = await _this.download()
    // console.log(res, '下载最后')
    wx.shareFileMessage({
      filePath: _this.data.FilePath,
      fileName: '走访统计信息.xls',
      success(data) {
        _this.hideSelect()
      },
      fail(res) {
        console.log(res, '分享报错的原因')
        // wx.showToast({
        //   title: JSON.stringify(res),
        //   icon: "none"
        // })
      }
    })
  },
  download() {
    // console.log(this.data.bankLevel,'开始导出')
    wx.showLoading({
      title: "导出中...",
    });
    const _this = this
    let type = ''
    if (this.data.bankLevel == 0) {
      type = 'level1'
    } else if (this.data.bankLevel == 1) {
      type = 'level2'
    } else if (this.data.bankLevel == 2) {
      type = 'level3'
    }
    let bankId = ''
    console.log(this.data.corpRole, 'corpRole')
    if (this.data.corpRole.indexOf('cbrc') == -1) {
      bankId = this.data.bankId
    }
    const params = {
      type: type,
      idList: _this.data.bankIds,
      bankId: bankId,
      batchId: this.data.batchId === '0' ? '' : this.data.batchId
      // corpType: wx.getStorageSync('corpType')
    }
    if (this.data.bankId) {
      params.bankId = this.data.bankId
    }
    console.log(params, '导出的传参')
    return new Promise(function (resolve, reject) {
      console.log(env.baseUrl)
      wx.request({
        // url: 'http://192.168.1.200:20100/visit/visitStatisticsExport',
        // url: 'https://fintech-wx.szjrgzjg.com/visit/visitStatisticsExport',
        // ======================
        // url: env.baseUrl + '/corpVisit/export_bank_statistics',
        url: env.baseUrl + '/corpVisit/export_bank_statistics_v2',
        data: params,
        method: 'POST',
        header: {
          "content-type": "application/json",
          "token": wx.getStorageSync('token')
        },
        responseType: "arraybuffer", //注意这里的responseType
        success: (result) => {
          console.log(result, '接口调用成功')
          let fileManager = wx.getFileSystemManager();
          _this.data.FilePath = wx.env.USER_DATA_PATH + "/" + 'zx' + '-' + '测试.xlsx';
          console.log(_this.data.FilePath, 'FilePath')
          fileManager.writeFile({
            data: result.data,
            filePath: _this.data.FilePath,
            encoding: "binary", //编码方式 
            success: res => {
              console.log("下载成功！", result);
              resolve('1111')
              // 电脑测试打开下面的注释代码
              // wx.openDocument({ 
              //   filePath: _this.data.FilePath,
              //   showMenu: true,
              //   fileType: "xls",
              //   success: result => {
              //     _this.setData({
              //       loadingHidden: true,
              //     })
              //     console.log("打开文档成功");
              //   },
              //   fail: err => {
              //     this.setData({
              //       loadingHidden: true,
              //     })
              //     console.log("打开文档失败", err);
              //   }
              // });
            },
            fail: res => {
              wx.showToast({
                title: '下载失败!',
                icon: 'none', //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
                duration: 2000, //停留时间
              })
            }
          })
        },
        fail(err) {
          console.log(err)
        }
      })
    })

  },

  // downloadWx () {
  //   wx.downloadFile({
  //     url: `http://192.168.1.200:20100/visit/visitStatisticsExport`,
  //     header: {
  //       token: wx.getStorageSync('token'),
  //       bankIds: this.data.bankIds
  //     },
  //     responseType: "arraybuffer",
  //     success (res) {
  //       console.log(res, '返回的二进制流');
  //       if (res.statusCode === 200) {
  //         console.log(res.tempFilePath, 'res.tempFilePath');
  //         // wx.getFileSystemManager().saveFile({
  //         //   tempFilePath: res.tempFilePath, // 传入一个本地临时文件路径, http://tmp/开头的
  //         //   filePath:
  //         //     wx.env.USER_DATA_PATH + "/" + "授权书模板" + ".doc", //此处文件名自定义，因为tempFilePath对应的是一大长串字符
  //         //   success (tres) {
  //         //     Toast("下载成功");
  //         //     //console.log('保存excel成功', tres) // res.savedFilePath 为一个本地缓存文件路径
  //         //     wx.openDocument({
  //         //       filePath: tres.savedFilePath,
  //         //       showMenu: true,
  //         //       success: (fres) => {
  //         //         Toast("打开excel成功");
  //         //         //console.log('打开excel成功', fres)
  //         //       },
  //         //     });
  //         //   },
  //         // });
  //       }
  //     },
  //   });
  //   // wx.downloadFile({
  //   //   url: '',
  //   //   success (res) {
  //   //     console.log('downloadFile', res)
  //   //     const filePath = res.tempFilePath
  //   //     wx.openDocument({
  //   //       filePath: filePath,
  //   //       success: function (ress) {
  //   //         console.log('打开文档成功', ress)
  //   //       },
  //   //       fail: function (err) {
  //   //         console.log('保存失败：', err)
  //   //       }
  //   //     })
  //   //   }
  //   // })
  // },
  hideSelect() {
    this.setData({
      showSelect: false,
    });
  },
  selectOne(e) {
    // console.log(e.currentTarget.dataset.name, 'eee')
    const oriProlistIndex = this.data.oriProlist.findIndex(val => val.name === e.currentTarget.dataset.name)
    const prolistIndex = this.data.prolist.findIndex(val => val.name === e.currentTarget.dataset.name)
    if (oriProlistIndex > -1) {
      this.data.oriProlist[oriProlistIndex].show = !this.data.oriProlist[oriProlistIndex].show
    }
    if (prolistIndex > -1) {
      this.data.prolist[prolistIndex].show = !this.data.prolist[prolistIndex].show
    }
    this.setData({
      oriProlist: this.data.oriProlist,
      prolist: this.data.prolist
    })

  },
  goSearch() {
    let prolist = JSON.parse(JSON.stringify(this.data.oriProlist)).filter(
      d =>
      d.name &&
      (d.name.indexOf(this.data.serach_pro.toLowerCase()) !== -1 ||
        d.name.indexOf(this.data.serach_pro.toUpperCase()) !== -1)
    );
    this.setData({
      prolist: prolist
    })
    // console.log(this.data.prolist, 'prolist')
  },
  goCopy() {
    let that = this;
    wx.setClipboardData({
      data: "www.baidu.com",
      success(res) {
        that.hideSelect();
        wx.showToast({
          title: "链接已复制",
          icon: "none",
        });
      },
    });
  },
  toprodetail(e) {
    // console.log(e.detail, "e.detail");
    if (e.detail.totalscore || e.detail.totalscore == 0) {
      wx.navigateTo({
        url: "/packageA/pages/homelink/measure_limit_detail/measure_limit_detail?corpKey=" +
          e.detail.corpKey,
      });
    } else {
      wx.showToast({
        title: "该企业尚未进行地方征信平台授权，请提交授权书后使用测额度功能",
        icon: "none",
      });
    }
  },
  // 滑动底部加载更多
  scrollBottom() {
    // this.onBottom();
  },
  getList() {
    var _this = this;
    this.setData({
      loading: true,
    });
    wx.showLoading({
      title: "加载中",
    });
    // const params = {
    //   pageSize: 50,
    //   pageNum: this.data.pageNum,
    //   keyword: _this.data.serach_pro,
    // };
    let params = {}
    let url = ''
    if (this.data.bankLevel == 0) {
      // 银监页面导出页面
      params = {
        corpType: wx.getStorageSync('corpType')
      };
      url = '/corpVisit/visit_statistic'
    } else if (this.data.bankLevel == 1) {
      // 一级银行导出页面
      params = {
        bankId: this.data.bankId,
      };
      url = '/corpVisit/level1_to_level2'
    } else if (this.data.bankLevel == '2') {
      // 二级银行导出页面
      params = {
        bankId: this.data.bankId,
      };
      url = '/corpVisit/level2_to_level3'
    }
    getApp()
      .globalData.request(url, params, "POST")
      .then((res) => {
        setTimeout(function () {
          wx.hideLoading();
        }, 500);
        var rstObj = res;
        rstObj.data = rstObj.data.filter(pre => pre)
        for (let i in rstObj.data) {
          rstObj.data[i].name = rstObj.data[i].bankName
        }
        console.log(rstObj, "res1111");
        // 过滤不必要的银行
        const noNeedList = ['创新工场', '渣打银行苏州分行', '北京银行苏州分行', '苏州金融租赁股份有限公司']
        const finalList = rstObj.data.filter(pre => !noNeedList.includes(pre.bankName))
        if (finalList.length > 0) {
          finalList.forEach(element => {
            element.show = false
          });
          _this.setData({
            oriProlist: JSON.parse(JSON.stringify(finalList)),
            prolist: JSON.parse(JSON.stringify(finalList)),
            // prosum: rstObj.data.total,
          });

          this.setData({
            loading: false,
          });
        }
      });
  },

  onBottom() {
    if (this.data.prolist.length >= this.data.prosum) return;
    this.data.pageNum++;
    this.getList();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      bankId: options.bankId || '',
      bankLevel: options.bankLevel,
      batchId: options.batchId
    })
    // const list = [{
    //   name: '苏州银行'
    // }, {
    //   name: '中国银行'
    // }]
    // this.setData({
    //   prolist: list,
    //   prosum: 2
    // })
    this.getList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});